//
//  SQLTool.m
//  SQL演练
//
//  Created by Guo Rui on 2017/10/25.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "SQLTool.h"
#import <sqlite3.h>

@implementation SQLTool {
    sqlite3 *db;
}

static SQLTool *tool = nil;
+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[SQLTool alloc] init];
    });
    return tool;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        /*
         -- 数据库是否存在 ---- YES -- 打开数据库
         |
         --- NO --- 创建数据库
         */
        int reslut = sqlite3_open("/Users/guorui/Desktop/dataBase/deom.sqlite", &db);
        if (reslut == SQLITE_OK) {
            NSLog(@"打开数据库成功");
        }
        else {
            NSLog(@"打开数据库失败");
        }
        
        [self createTable];
    }
    return self;
}

- (void)createTable
{
    char *sql = "CREATE TABLE IF NOT EXISTS t_student(id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer, score real DEFAULT 60)";
    char *errMsg = NULL;
    
    BOOL result = [self excute:sql errMsg:errMsg];
    if (result == SQLITE_OK) {
        NSLog(@"创建表成功");
    }
    else {
        NSLog(@"创建表失败 %s", errMsg);
    }
}

- (void)dropTable
{
    char *sql = "DROP TABLE IF EXISTS t_student";
    char *errMsg = NULL;
    BOOL result = [self excute:sql errMsg:errMsg];
    if (result == SQLITE_OK) {
        NSLog(@"删除表成功");
    }
    else {
        NSLog(@"删除表失败 %s", errMsg);
    }
}

- (void)renameTable
{
    char *sql = "ALTER TABLE t_student RENAME TO t_stu";
    char *errMsg = NULL;
    BOOL result = [self excute:sql errMsg:errMsg];
    if (result == SQLITE_OK) {
        NSLog(@"重命名表成功");
    }
    else {
        NSLog(@"重命名表失败 %s", errMsg);
    }
}

- (void)addColumn
{
    char *sql = "ALTER TABLE t_student ADD COLUMN address text DEFAULT 'shanghai'";
    char *errMsg = NULL;
    int result = sqlite3_exec(db, sql, nil, nil, &errMsg);
    if (result == SQLITE_OK) {
        NSLog(@"成功");
    }
    else {
        NSLog(@"失败 %s", errMsg);
    }
}

- (BOOL)excute:(const char *)sql errMsg:(char *)errMsg
{
    /**
     执行sql语句
     
     @param db 数据库句柄
     @param sql sql语句
     @param callback 回调
     @param param callback 中的第一个参数
     @param errMsg 错误信息
     @return 是否成功
     */
    int result = sqlite3_exec(db, sql, nil, nil, &errMsg);
//    if (result == SQLITE_OK) {
//        NSLog(@"执行成功");
//    }
//    else {
//        NSLog(@"%s", sql);
//        NSLog(@"执行失败 %s", errMsg);
//    }
    
    return result > 0 ? YES : NO;
}


@end
